package com.yuebao.controller;

import com.yuebao.api.TransactionService;
import com.yuebao.enumeration.ResponseCodeEnum;
import com.yuebao.model.pojo.Transaction;
import com.yuebao.request.RequestParameter;
import com.yuebao.result.EntityResponse;
import com.yuebao.utils.CacheClient;
import com.yuebao.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;

import static cn.hutool.core.lang.Console.log;
import static com.yuebao.result.HttpResponse.FAIL;
import static org.apache.catalina.manager.Constants.CHARSET;

@Slf4j
@RestController
@CrossOrigin(methods = {RequestMethod.POST})
@RequestMapping("/trade")
public class TradeController {
    
    @Resource
    private CacheClient cacheClient;
    
    @Resource
    private TransactionService transactionService;
    
    @PostMapping("")
    public String healthCheck(){
        return "";
    }

    @PostMapping("/buy")
    public EntityResponse<String> buyFund(@RequestBody @Valid RequestParameter<Transaction> preOrderDTO) throws IOException {
        
        Transaction preOrder = preOrderDTO.getBody();
        log.info("接收前端的预订单-->{}", JsonUtils.writeValueAsString(preOrder));
        try{
            String form = transactionService.buyFund(preOrder);
            if(StringUtils.isEmpty(form)){
                String token=cacheClient.pageCallBack(FAIL);
                return new EntityResponse<>(ResponseCodeEnum.FORBIDDEN,"下单失败" ,token);
            }
            
            String token = cacheClient.pageCallBack(form);
            return new EntityResponse<>(ResponseCodeEnum.SUCCESS,"下单成功",token);
        }catch (Exception e){
            log(e.getMessage());
            String token=  cacheClient.pageCallBack(FAIL);
            return new EntityResponse<>(ResponseCodeEnum.FORBIDDEN,"下单失败" ,token);
        }
    }
    @GetMapping("/page")
    public void getTradePage(@RequestParam("payPage") String token, HttpServletResponse httpResponse) throws IOException {
        String form =  cacheClient.readPageCallBack(token);
        log.info("====>page:{}"+form);
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
}
